var _CONFIG = {
	TYPE:'CLOTHING',
    JQXGRID: '#jqx_grid_view',
    BINDING_URI: base_url + 'cms/cp/product/binding_by_type/',
    EDITPANEL_URI:base_url + 'cms/cp/product/editpanel/',
    COMMIT_URI:base_url + 'cms/cp/product/oncommitdata/',
    DELETE_URI:base_url + 'cms/cp/product/ondeletedata/',
	SIZE_BINDING_URI:'/cms/cp/product/get_size_by_type/',
	COLOR_BINDING_URI:'/cms/cp/product/get_color_by_type/',
	CATE_BINDING_URI:'/cms/cp/category/binding/',
	CURRENCY_URI:'cms/cp/product/convertCurrency'
	
};


var _CP = (function() {
    var oTable;
    var that = this;
    var datafields = [
        {name: 'product_id', type: 'int'},
        {name: 'product_title'},
        {name: 'product_thumb'},
		{name: 'product_category_id',type: 'int'},
        {name: 'product_position',type: 'int'},
        {name: 'product_status',type: 'bool'},
        {name: 'product_insert', type: 'date'},
        {name: 'product_update', type: 'date'},
    ];
    var source,dataAdapter;
    return {
        onCommit: function(Params, Id,callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback(rsdata);
                        }
                    }
                }
            }).call();
        },
        creategrid:function(){
            
            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI+_CONFIG.TYPE,
                id:'product_id',
                root: 'rows',
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
                {
                    text: '', dataField: 'product_id', width: 60, filterable: false, sortable: false,editable: false,
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        var str = "";
                        if (value && value > 0) {
                            try {
                                //value = $.parseJSON(value);
                                str += "\
                                    <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_CP.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                                ";
                                str += "\
                                    <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_CP.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                                ";
                            } catch (e) {
                            }
                        }

                        return str;
                    }
                },
                {
                    text: 'TITLE'       , dataField: 'product_title',minWidth: 220
                },
                {
                    text: 'THUMB'     , dataField: 'product_thumb'   ,width:60,
                    filterable: false, sortable: false,editable: false,
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        if(value==undefined || value=='')
                            return '';
                        else{

                            return '<img onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + value + '"/>';
                        }
                    }
                },
				{
                    text: 'CATEGORY'       , dataField: 'product_category_id'    ,
                    width: 60, cellsalign: 'right', 
                    filterable: false, sortable: false,editable: false
                }, 
                {
                    text: 'POSITION'       , dataField: 'product_position'    ,
                    width: 60, cellsalign: 'right', 
                    filterable: false, sortable: false,editable: true,
                    columntype: 'numberinput', filtertype: 'number',
                    validation:function (cell, value) {
                        if (value < 0 || value > 99) {
                            return { result: false, message: "Position should be in the 0-99 interval." };
                        }
                        return true;
                    }
                },    
                {
                    text: 'STATUS'    , dataField: 'product_status' , cellsalign: 'center',
                    width: 60, columntype: 'checkbox', threestatecheckbox: false,
                    filterable: false, sortable: false,editable: true
                },
                {
                    text: 'CREATED'        , dataField: 'product_insert'      , width: 120,  cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false,editable: false
                },
                {
                    text: 'MODIFIELD'      , dataField: 'product_update'    , width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false,editable: false
                }
            ];
            
            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                editable: true,
                handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel=true;
                    }
                },

            }).bind('cellbeginedit', function (event) {
                that.cancel=false;
            }).bind('cellendedit', function (event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if(that.cancel)return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try{
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value!='')
                                _CP.onCommit({Title: _value}, _id);
                            break;
                        case 'Parent':
                            if (_value != _data.Parent)
                                _CP.onCommit({Parent: _value}, _id,function(){
                                    _CP.onRefresh();
                                });
                            break;
                        case 'Position':
                            if (_value != _data.Position)
                                _CP.onCommit({Position: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _CP.onCommit({Active: 'true'}, _id);
                            else
                                _CP.onCommit({Active: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        onInit  :   function(){
            this.creategrid();
        },
        onAddItem:function(){
            this.onEditItem(0);
        },
        onEditItem:function(Id){
            if (PENDING)
                return false;
			$('#viewport').hide();
            $('#_edit_panel_insite').show().html('<div class="base_loading" style="display: block;height: 60px"></div>');
            
            backend({
                url         :   _CONFIG.EDITPANEL_URI+_CONFIG.TYPE,
                data        :   {
                    Id  :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        $('#_edit_panel_insite').html('<span style="color:red">'+rsdata.message+'</span>');
                    }else{
						
                        $('#_edit_panel_insite').html(rsdata.htmlreponse);
						$('#_form_edit_panel select').select2();
						//if(Id>0) $('#_form_edit_panel .nav-tabs li').css({display:'list-item'});
						$( ".ui-sortable" ).sortable();
						addEditorBasic('product_content',420);
						addEditorBasic('product_content_vi',420);
						$("#product_related").tokenInput("/cms/cp/product/tokeninput/"+Id,{
                            propertyToSearch:'title',
                            //tokenValue:'Id',
                            preventDuplicates: true,
                            //queryParam:'sSearch'
                            prePopulate:rsdata.related,
//                            onResult: function (results) {
//                                $.each(results, function (index, value) {
//                                    value.id = value.Id;
//                                });
//                                return results;
//                            }
                        });
                    }
                }
            }).call();
        },
        onSave:function(){
            if( $('#_form_edit_panel').validationEngine('validate') === false)return false;
            var Params=$('#_form_edit_panel').serializeObject();
			Params.product_content = CKEDITOR.instances['product_content'].getData();
			Params.product_content_vi = CKEDITOR.instances['product_content_vi'].getData();
			Params.product_images=$('#product_images_list li div img').map(function() {
				return $(this).data('src');
			})
			.get()
			.join('\n');
            this.onCommit(Params,$('#Id').val(),function(rsdata){
                if($('#Id').val()===""){
					$('#Id').val(rsdata.last_id)
					//$('#_form_edit_panel .nav-tabs li').css({display:'list-item'});
					//$('a[href="#tab_product_color_size"]').click();
				}
				_CP.onRefresh();
				_CP.onCancel();
            });
            return false;
        },
        onCancel:function(){
            $('#_edit_panel_insite').hide();
			$('#viewport').show();
        },
        onDeleteItem:function(Id){
            backend_delete(_CONFIG.DELETE_URI,Id,function(){
                _CP.onRefresh();
            });
        },
        onRefresh:function(){
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
		onRefreshListBox:function(){
            $('#product_colors').jqxListBox('refresh');
			$('#product_sizes').jqxListBox('refresh');
        },
			
        onChangeSource:function(type){
			if(type===_CONFIG.TYPE)return;
            _CONFIG.TYPE=type;
            source.url= _CONFIG.BINDING_URI+_CONFIG.TYPE;
            this.onRefresh();
        },
		onMultiBrowseFile:function(){
			openKCFinderMulti(function(files){
				for(var i=0;i<files.length;i++){
					var node = '\
					<li class="ui-state-default">\
						<span class="ui-icon ui-icon-arrowthick-2-n-s" title="Drag to sort"></span>\
						<span class="select2-search-choice-close" onclick="_CP.onRemoveImageNode(this);" title="Remove"></span>\
						<div>\
							<img data-src="'+files[i]+'" src="'+files[i]+'" />\
						</div>\
					</li>';
					$('#product_images_list').append(node);
				}
			});
		},
		onRemoveImageNode:function(node){
			$(node).parents('li.ui-state-default').remove();
		}
    };
}());